<?php

namespace app\common\model\course;

use think\Model;


class Course extends Model
{





    // 表名
    protected $name = 'course';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
        'image_str',
        'file_str',
        'endtime_text',
        'trainingtime_text'
    ];
    public function getTrainingtimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['trainingtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setTrainingtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    public function getEndtimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['endtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setEndtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    public function getImageStrAttr($value, $data)
    {
        return isset($data['image']) && $data['image'] ? cdnurl($data['image'], true) : '';
    }
    public function getFileStrAttr($value, $data)
    {
        return isset($data['file']) && $data['file'] ? cdnurl($data['file'], true) : '';
    }
    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            if (isset($changed['category_id']) && $changed['category_id']) {
                $row->__set('type', Category::where('id', $changed['category_id'])->value('type'));
            }
        });
        self::beforeInsert(function ($row) {
            $changed = $row->getChangedData();
            if (isset($changed['category_id']) && $changed['category_id']) {
                $row->__set('type', Category::where('id', $changed['category_id'])->value('type'));
            }
        });
    }

    public function getTypeList()
    {
        return ['1' => __('Type 1'), '2' => __('Type 2')];
    }

    public function getSubjectList()
    {
        return ['1' => __('Subject 1'), '2' => __('Subject 2'), '3' => __('Subject 3')];
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function user()
    {
        return $this->hasMany(User::class, 'c_id', 'id');
    }


    public function category()
    {
        return $this->belongsTo('Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
